package com.treasure.mall.biz.repository.withdraw;

import com.treasure.mall.biz.base.JpaSearchableRepository;
import com.treasure.mall.biz.entity.withdraw.UserBankInfoPO;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zoul
 * @version 1.0
 * @date 2020/6/14 15:33
 * @Description
 */
@Repository
public interface UserBankInfoRepository extends JpaSearchableRepository<UserBankInfoPO, Long> {

    /**
     * 获取用户所有银行卡信息
     *
     * @param userId 用户Id
     * @return
     */
    @Query("select bank from UserBankInfoPO bank where bank.userPo.userId=?1 and bank.deleted=false")
    List<UserBankInfoPO> getListByUserId(Long userId);

    /**
     * 获取用户默认银行卡
     *
     * @param userId
     * @return
     */
    UserBankInfoPO findFirstByUserPo_UserIdAndDeletedIsFalseOrderByDefaultFlagDesc(Long userId);

    /**
     * 判断该银行卡用户是否添加过
     *
     * @param bankNo 银行卡号
     * @param userId 用户Id
     * @return
     */
    @Query("select count(bank.infoId) from  UserBankInfoPO bank where bank.userPo.userId=?2 and bank.bankNo=?1 and bank.deleted=false")
    int existsUserBankInfo(String bankNo, long userId);

    /**
     * 判断该银行卡是否属于该用户
     *
     * @param infoId 主键Id
     * @param userId 用户Id
     * @return
     */
    @Query("select count(bank.infoId) from  UserBankInfoPO bank where bank.userPo.userId=?2 and bank.infoId=?1")
    int existsUserBankInfo(Long infoId, long userId);

    /**
     * 设置默认银行卡
     *
     * @param userId 用户Id
     * @param infoId 主键Id
     */
    @Query("update UserBankInfoPO bank set bank.defaultFlag=true where bank.userPo.userId=?1 and bank.infoId=?2")
    @Modifying
    @Transactional(rollbackFor = RuntimeException.class)
    void setUserBankDefault(Long userId, Long infoId);

    /**
     * 移除用户默认银行卡
     *
     * @param userId 用户Id
     */
    @Query("update UserBankInfoPO bank set bank.defaultFlag=false where bank.userPo.userId=?1")
    @Modifying
    @Transactional(rollbackFor = RuntimeException.class)
    void delUserBankDefault(Long userId);

    /**
     * 获取用户有几张银行卡
     *
     * @param userId 用户Id
     * @return
     */
    @Query("select count(bank.infoId) from  UserBankInfoPO bank where bank.userPo.userId=?1 and bank.deleted=false")
    int countUserBankNum(Long userId);


    /**
     * 移除用户默认银行卡
     *
     * @param infoId 用户银行卡ID
     * @param userId 用户ID
     */
    @Query("update UserBankInfoPO bank set bank.deleted=true,bank.defaultFlag=false where bank.infoId=?1 and  bank.userPo.userId=?2")
    @Modifying
    @Transactional(rollbackFor = RuntimeException.class)
    void delUserBank(Long infoId, Long userId);
}

